package Com.Ring.TradingMobile.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.OrderInfo;
import Com.Ring.TradingMobile.Lib.PreTradeInfo;
import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.MarketInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import android.text.format.DateFormat;
import android.util.Log;

public class WebService {
	
	public static String NAMESPACE = "http://tempuri.org/";
	public static String SOAP_ACTION = "http://tempuri.org/";
	/*public static String ADDRESS_RTSERVICE = "http://10.0.2.2:80/RTDataServices/Service.asmx";
	public static String ADDRESS_ETRADE_SERVICE = "http://10.0.2.2:80/ETradeServices/ETradeServicesWebServices.asmx";
	public static String ADDRESS_AM_SERVICE = "http://10.0.2.2:80/AMServices/AccountManagerServices.asmx";*/
	
	public static String ADDRESS_RTSERVICE = "http://192.168.10.180/RTServiceM/Service.asmx";
	public static String ADDRESS_ETRADE_SERVICE = "http://192.168.10.180/ETradeServices/ETradeServicesWebServices.asmx";
	public static String ADDRESS_AM_SERVICE = "http://192.168.10.180/AMServicesM/AccountManagerServices.asmx";
	
	public static final String GetListStockInfos = "GetListStockInfos";
	public static final String GetListCompany = "GetListCompany";
	public static final String GetMarketInfo = "GetMarketInfo";
	public static final String GetPortfolio = "GetPortfolio";
	public static final String GetCashBalance = "GetCashBalance";
	public static final String GetAdvanceInfo = "GetAdvanceInfo";
	public static final String CheckAvailable = "CheckAvailable";
	
	public static final String GetListDanhMuc = "GetListDanhMuc";
	public static final String InsertDanhMuc = "InsertDanhMuc";
	public static final String DeleteDanhMuc = "DeleteDanhMuc";
	public static final String UpdateDanhMuc = "UpdateDanhMuc";
	public static final String InsertItemDanhMuc = "InsertItemDanhMuc";
	public static final String DeleteItemDanhMuc = "DeleteItemDanhMuc";
	public static final String GetListStockInforItemDanhMuc = "GetListStockInforItemDanhMuc";
	
	public static String TAG = "WebService";
	public WebService() {
		
	}
	
	public static String Request(String methodName, ArrayList<PropertyInfo> properties, String serviceAddress)
	{
		SoapObject request = new SoapObject(NAMESPACE, methodName);
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		
		for(PropertyInfo pro : properties)
		{
			request.addProperty(pro);			
		}
		
		envelope.setOutputSoapObject(request);
		
		HttpTransportSE http =new HttpTransportSE(serviceAddress);
		String soapAction = NAMESPACE + methodName;
		
		try 
		{
			LinkedList<HeaderProperty> reqHeaders = new LinkedList<HeaderProperty>();
			if (Session.GetSession() != null) {
				//Get cookie.
				reqHeaders = Session.GetSession();
			}
			
			@SuppressWarnings("unchecked")
			List<HeaderProperty> resHeaders = http.call(soapAction, envelope, reqHeaders);
			//Set cookie.
			Session.SetSession(resHeaders);
			
			JSONArray entries = new JSONArray("[" + envelope.getResponse().toString() + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));            
            
            //Check return code
            if(RetCode == RET_CODE.NOT_LOGIN.Value)
            {
            	Session.IsLogin = false;
            	return null;
            }
            
			return envelope.getResponse().toString();
		}
		catch(Exception ex) 
		{
			return "{}";
		}
	}
	
	public static int Update_Order (String accountNo, String pin, int accountType, String orderIdentifier, float newPrice) {
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraAccountNo = new PropertyInfo();
		paraAccountNo.setName("accountNo");
		paraAccountNo.setValue(accountNo);
		paraAccountNo.setNamespace(NAMESPACE);
		
		PropertyInfo paraPin = new PropertyInfo();
		paraPin.setNamespace(NAMESPACE);
		paraPin.setName("pin");
		paraPin.setValue(pin);
		
		PropertyInfo paraAccountType = new PropertyInfo();
		paraAccountType.setNamespace(NAMESPACE);
		paraAccountType.setName("accountType");
		paraAccountType.setValue(0);
		
		PropertyInfo paraOrderIdentifier = new PropertyInfo();
		paraOrderIdentifier.setNamespace(NAMESPACE);
		paraOrderIdentifier.setName("orderIdentifier");
		paraOrderIdentifier.setValue(orderIdentifier);
		
		PropertyInfo paraNewPrice = new PropertyInfo();
		paraNewPrice.setNamespace(NAMESPACE);
		paraNewPrice.setName("newPrice");
		paraNewPrice.setValue(newPrice);
		
		properties.add(paraAccountNo);
		properties.add(paraPin);
		properties.add(paraAccountType);
		properties.add(paraOrderIdentifier);
		properties.add(paraNewPrice);
		
		SoapObject request = new SoapObject(NAMESPACE, "UpdateOrder");
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		
		for(PropertyInfo pro : properties)
		{
			request.addProperty(pro);			
		}
		
		envelope.setOutputSoapObject(request);
		
		HttpTransportSE http =new HttpTransportSE(ADDRESS_ETRADE_SERVICE);
		String soapAction = NAMESPACE+ "UpdateOrder";
		
		envelope.addMapping(NAMESPACE, "Decimal", MarshalFloat.class);
		
		MarshalFloat md = new MarshalFloat();
		md.register(envelope);
		
		try 
		{
			LinkedList<HeaderProperty> reqHeaders = new LinkedList<HeaderProperty>();
			if (Session.GetSession() != null) {
				//Get cookie.
				reqHeaders = Session.GetSession();
			}
			
			@SuppressWarnings("unchecked")
			List<HeaderProperty> resHeaders = http.call(soapAction, envelope, reqHeaders);
			//Set cookie.
			Session.SetSession(resHeaders);
			
			JSONArray entries = new JSONArray("[" + envelope.getResponse().toString() + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));            
            
            //Check return code
            if(RetCode == RET_CODE.NOT_LOGIN.Value)
            {
            	Session.IsLogin = false;
            }
            
			return RetCode;
		}
		catch(Exception ex) 
		{
			return RET_CODE.SYSTEM_ERROR.Value;
		}
	}
	
	public static String[] GetAllMarketStatus()
	{
		try
		{
			String[] marketStatus = new String[3];
			
			String response = Request("GetAllMarketStatus", new ArrayList<PropertyInfo>(), ADDRESS_ETRADE_SERVICE);
			JSONArray entries = new JSONArray("[" + response + "]");            
            JSONObject post = entries.getJSONObject(0);
            
            entries = new JSONArray(post.getString("Result"));
            
            for(int i= 0; i< 3; i++)
            	marketStatus[i] = entries.getString(i);
            
            return marketStatus;
		}
		catch(Exception ex)
		{
			Log.d("TAG", "KhÃ´ng xÃ¡c Ä‘á»‹nh tráº¡ng thÃ¡i thá»‹ trÆ°á»�ng!");
			return new String[] {"U","U","U"};
		}
	}
	
	public static PreTradeInfo GetPreTradeInfo(String _subCustAccount, String strSymbol, int _accountType, String side)
	{
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraSubCustAccount = new PropertyInfo();
		paraSubCustAccount.setName("accountNo");
		paraSubCustAccount.setValue(_subCustAccount);
		paraSubCustAccount.setNamespace(NAMESPACE);
		
		PropertyInfo paraSymbol = new PropertyInfo();
		paraSymbol.setName("symbol");
		paraSymbol.setValue(strSymbol);
		paraSymbol.setNamespace(NAMESPACE);
		
		PropertyInfo paraAccountType = new PropertyInfo();
		paraAccountType.setName("accountType");
		paraAccountType.setValue(_accountType);
		paraAccountType.setNamespace(NAMESPACE);
		
		PropertyInfo paraSide = new PropertyInfo();
		paraSide.setName("sIde");
		paraSide.setValue(side);
		paraSide.setNamespace(NAMESPACE);
		
		properties.add(paraSubCustAccount);
		properties.add(paraSymbol);
		properties.add(paraAccountType);
		properties.add(paraSide);
		
		try 
		{
			PreTradeInfo preTradeInfo = new PreTradeInfo(); 
					
			String getPreTradeInfoReturn = Request("GetPreTradeInfo", properties, ADDRESS_ETRADE_SERVICE);
			
			JSONArray entries = new JSONArray("[" + getPreTradeInfoReturn + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));            
            
            //Check return code                        
            if(RetCode != RET_CODE.SUCCESS.Value)
            {
            	return null;
            }                      
            
            JSONArray resultEntries = new JSONArray("[" + post.getString("Result") + "]");
            post = resultEntries.getJSONObject(0);
            
            JSONArray stockInfoEntries = new JSONArray("[" + post.getString("StockInfo") + "]");
            JSONArray cashAvailableEntries = new JSONArray("[" + post.getString("CashAvailable") + "]");

            if(side.equals("S"))            
            	preTradeInfo.VolumeCanSell = Integer.parseInt(post.getString("VolumeCanSell"));
            
            post = stockInfoEntries.getJSONObject(0);            
            preTradeInfo.MarketId = Integer.parseInt(post.getString("MarketID"));
            preTradeInfo.Ceiling = Float.parseFloat(post.getString("Ceiling"));
            preTradeInfo.Floor = Float.parseFloat(post.getString("Floor"));
            preTradeInfo.RefPrice = Float.parseFloat(post.getString("RefPrice"));
            preTradeInfo.AvrPrice = Float.parseFloat(post.getString("AvrPrice"));
            post = cashAvailableEntries.getJSONObject(0);
            preTradeInfo.AvailableCash = Float.parseFloat(post.getString("BuyCredit"));
                                  
            return preTradeInfo;
		}
		catch(Exception ex)
		{
			return null;
		}
	}
	
	public static float GetCashBalance(String account, int accountType)
	{
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraSubAccountNo = new PropertyInfo();
		paraSubAccountNo.setName("subAccountNo");
		paraSubAccountNo.setValue(account);
		paraSubAccountNo.setNamespace(NAMESPACE);
		
		PropertyInfo paraAccountType = new PropertyInfo();
		paraAccountType.setNamespace(NAMESPACE);
		paraAccountType.setName("accountType");
		paraAccountType.setValue(accountType);		
		
		properties.add(paraSubAccountNo);
		properties.add(paraAccountType);
		
		try 
		{
			String putOrderReturn = Request("GetCashBalance", properties, ADDRESS_ETRADE_SERVICE);
			
			JSONArray entries = new JSONArray("[" + putOrderReturn + "]");            
            JSONObject post = entries.getJSONObject(0);
            
            int RetCode = Integer.parseInt(post.getString("RetCode"));
            
            //Check return code
            if(RetCode != RET_CODE.SUCCESS.Value)
            {
            	return -1;
            }            
            
            entries = new JSONArray("[" +post.getString("Result") + "]");
            post = entries.getJSONObject(0);
            
            float BuyCredit = Float.parseFloat(post.getString("BuyCredit"));
            
            return BuyCredit;
		}
		catch(Exception ex) 
		{
			Log.d("TAG", "System error!");
			return Float.NaN;
		}
	}
	
	public static String NewestOrdStatus(String accountNo, int marketId, String stock, String side, String conPrice, boolean isWaitingMatch, boolean isMatched, boolean isSemiMatched, boolean isCancelled, boolean isRejected, boolean isProcessing, boolean isFirstTime, int position)
	{
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraSubAccountNo = new PropertyInfo();
		paraSubAccountNo.setName("accountNo");
		paraSubAccountNo.setValue(accountNo);
		paraSubAccountNo.setNamespace(NAMESPACE);
		
		PropertyInfo paraMarketId = new PropertyInfo();
		paraMarketId.setNamespace(NAMESPACE);
		paraMarketId.setName("marketId");
		paraMarketId.setValue(marketId);				
		
		PropertyInfo paraStock = new PropertyInfo();
		paraStock.setNamespace(NAMESPACE);
		paraStock.setName("stock");
		paraStock.setValue(stock);
		
		PropertyInfo paraSide = new PropertyInfo();
		paraSide.setNamespace(NAMESPACE);
		paraSide.setName("side");
		paraSide.setValue(side);
		
		PropertyInfo paraConPrice = new PropertyInfo();
		paraConPrice.setNamespace(NAMESPACE);
		paraConPrice.setName("conPrice");
		paraConPrice.setValue(conPrice);
		
		PropertyInfo paraIsWaitingMatch = new PropertyInfo();
		paraIsWaitingMatch.setNamespace(NAMESPACE);
		paraIsWaitingMatch.setName("isWaitingMatch");
		paraIsWaitingMatch.setValue(isWaitingMatch);
		
		PropertyInfo paraIsMatched = new PropertyInfo();
		paraIsMatched.setNamespace(NAMESPACE);
		paraIsMatched.setName("isMatched");
		paraIsMatched.setValue(isMatched);
		
		PropertyInfo paraIsSemiMatched = new PropertyInfo();
		paraIsSemiMatched.setNamespace(NAMESPACE);
		paraIsSemiMatched.setName("isSemiMatched");
		paraIsSemiMatched.setValue(isSemiMatched);
		
		PropertyInfo paraIsCancelled = new PropertyInfo();
		paraIsCancelled.setNamespace(NAMESPACE);
		paraIsCancelled.setName("isCancelled");
		paraIsCancelled.setValue(isCancelled);
		
		PropertyInfo paraIsRejected = new PropertyInfo();
		paraIsRejected.setNamespace(NAMESPACE);
		paraIsRejected.setName("isRejected");
		paraIsRejected.setValue(isRejected);
		
		PropertyInfo paraIsProcessing = new PropertyInfo();
		paraIsProcessing.setNamespace(NAMESPACE);
		paraIsProcessing.setName("isProcessing");
		paraIsProcessing.setValue(isProcessing);
		
		PropertyInfo paraIsFirstTime = new PropertyInfo();
		paraIsFirstTime.setNamespace(NAMESPACE);
		paraIsFirstTime.setName("isFirstTime");
		paraIsFirstTime.setValue(isFirstTime);
		
		PropertyInfo paraPosition = new PropertyInfo();
		paraPosition.setNamespace(NAMESPACE);
		paraPosition.setName("position");
		paraPosition.setValue(position);		
		
		
		properties.add(paraSubAccountNo);
		properties.add(paraMarketId);
		properties.add(paraStock);
		properties.add(paraSide);
		properties.add(paraConPrice);
		properties.add(paraIsWaitingMatch);
		properties.add(paraIsMatched);
		properties.add(paraIsSemiMatched);
		properties.add(paraIsCancelled);
		properties.add(paraIsRejected);
		properties.add(paraIsProcessing);
		properties.add(paraIsFirstTime);
		properties.add(paraPosition);		
		
		try 
		{
			String newestOrdStatusReturn = Request("NewestOrdStatus", properties, ADDRESS_ETRADE_SERVICE);
			
			return newestOrdStatusReturn;
		}
		catch(Exception ex) 
		{
			Log.d("TAG", "System error!");
			return "";
		}
	}
	
	public static ArrayList<OrderInfo> GetListNewestOrder(String accountNo)
	{
		ArrayList<OrderInfo> result = new ArrayList<OrderInfo>(); 
		
		String newestOrderStatusStr = NewestOrdStatus(accountNo, 4, "", "", "", true, true, true, true, true, true, true, 1);
		
		if(newestOrderStatusStr.equals(""))
			return result;
		
		try 
		{
			JSONArray entries = new JSONArray("[" + newestOrderStatusStr + "]");
			JSONObject post = entries.getJSONObject(0);
			
			int RetCode = Integer.parseInt(post.getString("RetCode"));
	        
	        //Check return code
	        if(RetCode != RET_CODE.SUCCESS.Value)
	        {
	        	return result;
	        }            
	        
	        entries = new JSONArray("[" +post.getString("Result") + "]");
	        post = entries.getJSONObject(0);
	        
	        entries = new JSONArray(post.getString("Data"));
	        
	        DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.0" );	        	        
	        
	        for(int i=0; i< entries.length(); i++)
	        {
	        	post = entries.getJSONObject(i);
	        	OrderInfo order = new OrderInfo();
	        	
	        	try
	        	{
		        	order.OrderId = post.getString("OrderIdentifier");
		        	order.StockSymbol = post.getString("SecSymbol");
		        	order.Volume = Integer.parseInt(post.getString("Volume"));
		        	order.RemainingVolume = Integer.parseInt(post.getString("RemainingVolume"));
		        	order.Price = Float.parseFloat(post.getString("Price"));
		        	order.Floor = Float.parseFloat(post.getString("Floor"));
		        	order.Ceiling = Float.parseFloat(post.getString("Ceiling"));
		        	order.Ref = Float.parseFloat(post.getString("RefPrice"));
		        	order.Side = post.getString("Side");
		        	order.ExecutedVol = Integer.parseInt(post.getString("ExecutedVol"));		        	
		        	order.CancelledVolume = Integer.parseInt(post.getString("CancelledVolume"));
		        	order.OrderStatus = Integer.parseInt(post.getString("OrderStatus"));	        		        		        	
		        	order.CanCancel = Boolean.parseBoolean(post.getString("CanCancel"));
		        	order.CanUpdate = Boolean.parseBoolean(post.getString("CanUpdate"));
		        	order.ExecutedPrice = Float.parseFloat(post.getString("ExecutedPrice"));
	        	}
	        	catch (Exception e) {
	    			Log.d("TAG", "NewestOrderStatus parseing error at orderid:" + order.OrderId);
	    		}                 
	        	result.add(order);
	        }
	        
	        return result;
		} 
		catch (JSONException e) {
			Log.d("TAG", "NewestOrderStatus parseing error!");
			return result;
		}                                   		
		
	}
	
	public static float GetFee()
	{
		return 1;
	}
	
	public static int PutOrder(int market, String accountNo, String pin, String secSymbol, String side, int volume, float price, String conPrice, int accountType, String orderSource)
	{
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraMarket = new PropertyInfo();
		paraMarket.setNamespace(NAMESPACE);
		paraMarket.setName("market");
		paraMarket.setValue(market);		
		
		PropertyInfo paraAccountNo = new PropertyInfo();
		paraAccountNo.setNamespace(NAMESPACE);
		paraAccountNo.setName("accountNo");
		paraAccountNo.setValue(accountNo);
		
		PropertyInfo paraPin = new PropertyInfo();
		paraPin.setNamespace(NAMESPACE);
		paraPin.setName("pin");
		paraPin.setValue(pin);
		
		PropertyInfo paraSecSymbol = new PropertyInfo();
		paraSecSymbol.setNamespace(NAMESPACE);
		paraSecSymbol.setName("secSymbol");
		paraSecSymbol.setValue(secSymbol);
		
		PropertyInfo paraSide = new PropertyInfo();
		paraSide.setNamespace(NAMESPACE);
		paraSide.setName("side");
		paraSide.setValue(side);
		
		PropertyInfo paraVolume = new PropertyInfo();
		paraVolume.setNamespace(NAMESPACE);
		paraVolume.setName("volume");
		paraVolume.setValue(volume);
		
		PropertyInfo paraPrice = new PropertyInfo();
		paraPrice.setNamespace(NAMESPACE);
		paraPrice.setName("price");
		paraPrice.setValue(price);
		
		PropertyInfo paraConPrice = new PropertyInfo();
		paraConPrice.setNamespace(NAMESPACE);
		paraConPrice.setName("conPrice");
		paraConPrice.setValue(conPrice);
		
		PropertyInfo paraAccountType = new PropertyInfo();
		paraAccountType.setNamespace(NAMESPACE);
		paraAccountType.setName("accountType");
		paraAccountType.setValue(accountType);
		
		PropertyInfo paraOrderSource = new PropertyInfo();
		paraOrderSource.setNamespace(NAMESPACE);
		paraOrderSource.setName("orderSource");
		paraOrderSource.setValue(orderSource);
		
		properties.add(paraMarket);
		properties.add(paraAccountNo);
		properties.add(paraPin);
		properties.add(paraSecSymbol);
		properties.add(paraSide);
		properties.add(paraVolume);
		properties.add(paraPrice);
		properties.add(paraConPrice);
		properties.add(paraAccountType);
		properties.add(paraOrderSource);
		
		SoapObject request = new SoapObject(NAMESPACE, "PutOrder");
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		
		for(PropertyInfo pro : properties)
		{
			request.addProperty(pro);			
		}
		
		envelope.setOutputSoapObject(request);
		
		HttpTransportSE http =new HttpTransportSE(ADDRESS_ETRADE_SERVICE);
		String soapAction = NAMESPACE+ "PutOrder";
		
		envelope.addMapping(NAMESPACE, "Decimal", MarshalFloat.class);
		
		MarshalFloat md = new MarshalFloat();
		md.register(envelope);
		
		try 
		{
			LinkedList<HeaderProperty> reqHeaders = new LinkedList<HeaderProperty>();
			if (Session.GetSession() != null) {
				//Get cookie.
				reqHeaders = Session.GetSession();
			}
			
			@SuppressWarnings("unchecked")
			List<HeaderProperty> resHeaders = http.call(soapAction, envelope, reqHeaders);
			//Set cookie.
			Session.SetSession(resHeaders);
			
			JSONArray entries = new JSONArray("[" + envelope.getResponse().toString() + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));            
            
            //Check return code
            if(RetCode == RET_CODE.NOT_LOGIN.Value)
            {
            	Session.IsLogin = false;
            }
            
			return RetCode;
		}
		catch(Exception ex) 
		{
			return RET_CODE.SYSTEM_ERROR.Value;
		}
	}
	
	public static int CancelOrder(String orderIdentifier, String accountNo) {
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraOrderIdentifier = new PropertyInfo();
		paraOrderIdentifier.setName("orderIdentifier");
		paraOrderIdentifier.setValue(orderIdentifier);
		paraOrderIdentifier.setNamespace(NAMESPACE);
		
		PropertyInfo paraAccountNo = new PropertyInfo();
		paraAccountNo.setNamespace(NAMESPACE);
		paraAccountNo.setName("accountNo");
		paraAccountNo.setValue(accountNo);
		
		properties.add(paraOrderIdentifier);
		properties.add(paraAccountNo);
		
		try 
		{
			String requestReturn = Request("CancelOrder", properties, ADDRESS_ETRADE_SERVICE);
			
			JSONArray entries = new JSONArray("[" + requestReturn + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));
                        
            return RetCode;
		}
		catch(Exception ex) 
		{
			return RET_CODE.SYSTEM_ERROR.Value;
		}
	}
	
	public static int Login (String user, String password) {
		ArrayList<PropertyInfo> properties = new ArrayList<PropertyInfo>();
		
		PropertyInfo paraUsername = new PropertyInfo();
		paraUsername.setName("username");
		paraUsername.setValue(user);
		paraUsername.setNamespace(NAMESPACE);
		
		PropertyInfo paraPassword = new PropertyInfo();
		paraPassword.setNamespace(NAMESPACE);
		paraPassword.setName("password");
		paraPassword.setValue(password);
		
		PropertyInfo paraAuthType = new PropertyInfo();
		paraAuthType.setNamespace(NAMESPACE);
		paraAuthType.setName("authType");
		paraAuthType.setValue(0);
		
		properties.add(paraUsername);
		properties.add(paraPassword);
		properties.add(paraAuthType);
		
		try 
		{
			String loginReturn = Request("Login", properties, ADDRESS_ETRADE_SERVICE);
			
			JSONArray entries = new JSONArray("[" + loginReturn + "]");            
            JSONObject post = entries.getJSONObject(0);                
            int RetCode = Integer.parseInt(post.getString("RetCode"));
            
            JSONArray resultEntries = new JSONArray("[" + post.getString("Result") + "]");
            post = resultEntries.getJSONObject(0);
            
            JSONArray subCustAccountCollectionEntries = new JSONArray(post.getString("SubCustAccountCollection"));
            Session.subCustAccounts = new ArrayList<String>();
            for(int i=0; i<subCustAccountCollectionEntries.length(); i++)
            {
            	JSONObject obj = subCustAccountCollectionEntries.getJSONObject(i);
            	Session.subCustAccounts.add(obj.getString("SubCustAccountId"));
            }
            
            return RetCode;
		}
		catch(Exception ex) 
		{
			return RET_CODE.SYSTEM_ERROR.Value;
		}
	}
	
	public MarketInfo GetMarketInfoAndStatus (int marketId) {
		SoapObject request = new SoapObject(NAMESPACE, GetMarketInfo);
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		PropertyInfo paraMarketId = new PropertyInfo();
		paraMarketId.setName("marketID");
		paraMarketId.setValue(marketId);
		paraMarketId.setType(int.class);
		paraMarketId.setNamespace(NAMESPACE);
		request.addProperty(paraMarketId);
		envelope.setOutputSoapObject(request);
		Log.d(TAG, request.toString());
		HttpTransportSE http =new HttpTransportSE(ADDRESS_RTSERVICE);
		String soapAction = NAMESPACE+GetMarketInfo;
		try {
			http.call(soapAction, envelope);
			JSONObject responJson = new JSONObject(envelope.getResponse().toString());
			JSONArray objArray = responJson.getJSONArray("Result");
			JSONObject obj = objArray.getJSONObject(0);
			MarketInfo marketInfo = new MarketInfo();
			marketInfo.marketid = obj.getInt(MarketInfo.MARKET_ID);
			//marketInfo.CountFloor = Float.parseFloat(obj.getString(MarketInfo.COUNT_FLOOR));
			marketInfo.IndexChanged = Float.parseFloat(obj.getString(MarketInfo.INDEX_CHANGED));
			marketInfo.SetIndex = Float.parseFloat(obj.getString(MarketInfo.SET_INDEX));
			marketInfo.Status = obj.getString(MarketInfo.STATUS);
			marketInfo.Time = obj.getInt(MarketInfo.TIME);
			marketInfo.TotalShares = Float.parseFloat(obj.getString(MarketInfo.TOTAL_SHARES));
			marketInfo.TotalValues = Float.parseFloat(obj.getString(MarketInfo.TOTAL_VALUES));
			marketInfo.TradeDate = obj.getString(MarketInfo.TRADE_DATE);
			if(!marketInfo.TradeDate.equals("")) {
				marketInfo.TradeDate = marketInfo.TradeDate.substring(6, marketInfo.TradeDate.length()-2);
				marketInfo.TradeDate = DateFormat.format("yyyy-MM-dd", Long.parseLong(marketInfo.TradeDate)).toString();
				Log.d(TAG, marketInfo.TradeDate);
			}
			return marketInfo;
		}catch(Exception ex) {
			Log.d(TAG, ex.toString());
			return null;
		}
	}
	
	public List<CompanyInfo> GetCompanyList(int marketId){
		SoapObject request = new SoapObject(NAMESPACE, GetListCompany);
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		PropertyInfo paraMarketId = new PropertyInfo();
		paraMarketId.setName("marketID");
		paraMarketId.setValue(marketId);
		paraMarketId.setType(int.class);
		request.addProperty(paraMarketId);
		envelope.setOutputSoapObject(request);
		Log.d(TAG, request.toString());
		HttpTransportSE http =new HttpTransportSE(ADDRESS_RTSERVICE);
		String soapAction = NAMESPACE+GetListCompany;
		try {
			http.call(soapAction, envelope);
			JSONObject responJson = new JSONObject(envelope.getResponse().toString());
			JSONArray companyArray = responJson.getJSONArray("Result");
			List<CompanyInfo> companyInfoList = new ArrayList<CompanyInfo>(); 
			for(int i=0; i<companyArray.length(); i++) {
				JSONObject obj = companyArray.getJSONObject(i);
				CompanyInfo company = new CompanyInfo();
				company.Code = obj.getString(CompanyInfo.CODE);
				company.MarketId = obj.getInt(CompanyInfo.MARKETID);
				company.FullName = obj.getString(CompanyInfo.FULLNAME);
				companyInfoList.add(company);
			}
			return companyInfoList;
		}catch(Exception ex) {
			Log.d(TAG, ex.toString());
			return null;
		}
	}
	
	public List<CompanyInfo> GetCompanyList(int marketId, int langId){
		SoapObject request = new SoapObject(NAMESPACE, GetListCompany);
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		PropertyInfo paraMarketId = new PropertyInfo();
		paraMarketId.setName("marketID");
		paraMarketId.setValue(marketId);
		paraMarketId.setType(int.class);
		PropertyInfo paraLangId = new PropertyInfo();
		paraLangId.setName("languageId");
		paraLangId.setValue(langId);
		paraLangId.setType(int.class);
		request.addProperty(paraMarketId);
		request.addProperty(paraLangId);
		envelope.setOutputSoapObject(request);
		Log.d(TAG, request.toString());
		HttpTransportSE http =new HttpTransportSE(ADDRESS_RTSERVICE);
		String soapAction = NAMESPACE+GetListCompany;
		try {
			http.call(soapAction, envelope);
			JSONObject responJson = new JSONObject(envelope.getResponse().toString());
			JSONArray companyArray = responJson.getJSONArray("Result");
			List<CompanyInfo> companyInfoList = new ArrayList<CompanyInfo>(); 
			for(int i=0; i<companyArray.length(); i++) {
				JSONObject obj = companyArray.getJSONObject(i);
				CompanyInfo company = new CompanyInfo();
				company.Code = obj.getString(CompanyInfo.CODE);
				company.MarketId = obj.getInt(CompanyInfo.MARKETID);
				company.FullName = obj.getString(CompanyInfo.FULLNAME);
				companyInfoList.add(company);
			}
			return companyInfoList;
		}catch(Exception ex) {
			Log.d(TAG, ex.toString());
			return null;
		}
	}
	
	public List<StockInfo> GetListStockInfo(String listCode, int langId){
		SoapObject request = new SoapObject(NAMESPACE, GetListStockInfos);
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		
		PropertyInfo paraListCode = new PropertyInfo();
		paraListCode.setName("listCodes");
		paraListCode.setValue(listCode);
		paraListCode.setNamespace(NAMESPACE);
		PropertyInfo paraLangId = new PropertyInfo();
		paraLangId.setNamespace(NAMESPACE);
		paraLangId.setName("languageId");
		paraLangId.setValue(String.valueOf(langId));
		
		request.addProperty(paraListCode);
		request.addProperty(paraLangId);
		envelope.setOutputSoapObject(request);
		HttpTransportSE http =new HttpTransportSE(ADDRESS_RTSERVICE);
		String soapAction = NAMESPACE+GetListStockInfos;
		try {
			http.call(soapAction, envelope);
			JSONObject responJson = new JSONObject(envelope.getResponse().toString());
			JSONArray stockArray = responJson.getJSONArray("Result");
			List<StockInfo> stockInfoList = new ArrayList<StockInfo>(); 
			for(int i=0; i<stockArray.length(); i++) {
				JSONObject obj = stockArray.getJSONObject(i);
				StockInfo stock = new StockInfo();
				stock.Symbol = obj.getString(StockInfo.SYMBOL);
				stock.RefPrice = Float.parseFloat(obj.getString(StockInfo.REF_PRICE));
				stock.CeilPrice = Float.parseFloat(obj.getString(StockInfo.CEIL_PRICE));
				stock.FloorPrice = Float.parseFloat(obj.getString(StockInfo.FLOOR_PRICE));
				stock.PriceMatch = Float.parseFloat(obj.getString(StockInfo.PRICE_MATCH));
				stock.Changed = Float.parseFloat(obj.getString(StockInfo.CHANGED));
				stock.PerChanged = Float.parseFloat(obj.getString(StockInfo.PER_CHANGED));
				stock.VolumeMatch = Float.parseFloat(obj.getString(StockInfo.VOLUME_MATCH));
				stock.TotalMatch = Float.parseFloat(obj.getString(StockInfo.TOTAL_MATCH));

				stock.BestPriceBuy = Float.parseFloat(obj.getString(StockInfo.BEST_PRICE_BUY));
				stock.BestVolbuy = Float.parseFloat(obj.getString(StockInfo.BEST_VOL_BUY));
				stock.BestPriceSell = Float.parseFloat(obj.getString(StockInfo.BEST_PRICE_SELL));
				stock.BestVolSell = Float.parseFloat(obj.getString(StockInfo.BEST_VOL_SELL));
				stock.TradeDate = obj.getString(StockInfo.TRADE_DATE);
				if(!stock.TradeDate.equals("")) {
					stock.TradeDate = stock.TradeDate.substring(6, stock.TradeDate.length()-2);
					stock.TradeDate = DateFormat.format("yyyy-MM-dd", Long.parseLong(stock.TradeDate)).toString();
					Log.d(TAG, stock.TradeDate);
				}
				stockInfoList.add(stock);
			}
			return stockInfoList;
		}catch(Exception ex) {
			Log.d(TAG, ex.toString()+"-"+listCode);
			return null;
		}
	}		
	public static boolean IsConnected() {
		SoapObject request = new SoapObject(NAMESPACE, CheckAvailable+"-");
		SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
		
		envelope.setOutputSoapObject(request);
		HttpTransportSE http =new HttpTransportSE(ADDRESS_RTSERVICE);
		String soapAction = NAMESPACE+CheckAvailable+"-";
		try {
			http.call(soapAction, envelope);
			if(envelope.getResponse().toString()=="1")
				return true;
		}catch(Exception ex) {
			return false;
		}
		return false;
	}	
}